import xlrd


def read_excel(path, sheet_name, cus_row=-1):
    wb = xlrd.open_workbook(path)
    # 通过sheet_by_name()或者sheet_by_index()方法打开工作表对象
    sheet_1 = wb.sheet_by_name(sheet_name)  # 或者sheet_1 = wb.sheet_by_index(0)
    # 通过ncols和nrows 分别获得工作表的列数和行数
    row = sheet_1.nrows
    if cus_row > 0:
        row = cus_row
    clo = sheet_1.ncols
    # 通过cell().value方法获得单元格的数值
    header = {}
    row_list = []
    for i in range(0, clo):
        sheet_1.cell(0, i).value
        header[i] = sheet_1.cell(0, i).value
    for i in range(1, row):
        excel_row = {}
        for j in range(0, clo):
            excel_row[header[j]] = sheet_1.cell(i, j).value
        row_list.append(excel_row)
    return row_list



# ex 1   1,2,3  1-10   1,4,5-10,12,14-18
def filter_list_row(cus_range, row_list):
    real_range = []
    if "," in cus_range:
        arr = cus_range.split(',')
        for row in arr:
            if "-" in row:
                sub_arr = row.split('-')
                assert int(sub_arr[1]) > int(sub_arr[0]), "range error"

                for i in range(int(sub_arr[0]), int(sub_arr[1]) + 1):
                    real_range.append(i)
            else:
                real_range.append(int(row))
    elif "-" in cus_range:
        sub_arr = cus_range.split('-')
        assert int(sub_arr[1]) > int(sub_arr[0]), "range error"
        for i in range(int(sub_arr[0]), int(sub_arr[1]) + 1):
            real_range.append(i)
    else:
        real_range.append(int(cus_range))
    real_list = []
    real_range = list(set(real_range))
    for j in range(len(real_range)):
        real_list.append(row_list[int(real_range[j]) - 1])

    return real_list
